<template>
  <view class="page-container">
    <!-- 顶部蓝色背景 -->
    <view class="header-background">
      <!-- 门店信息 -->
      <view class="store-header">
        <view class="store-logo-container">
          <image class="store-logo" src="/static/logo.png" mode="aspectFill"></image>
        </view>
        <view class="store-info">
          <text class="store-name">{{ currentStoreName }}</text>
          <view class="store-status">
            <text class="status-tag" :style="{ backgroundColor: getStatusColor(currentStoreStatus.type) }">{{ currentStoreStatus.text }}</text>
            <view class="switch-store-btn" @click="switchStore">
              <uni-icons type="loop" size="14" color="#fff"></uni-icons>
              <text>切换门店</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 今日数据统计 -->
      <view class="today-stats">
        <view class="stats-item">
          <text class="stats-label">今日支付金额(元)</text>
          <text class="stats-value">{{ ((statistics.today_revenue || 0) / 100).toFixed(2) }}</text>
          <text class="stats-compare">昨日 ¥{{ ((statistics.yesterday_revenue || 0) / 100).toFixed(2) }}</text>
          <text class="stats-trend" :class="getTrendClass(statistics.today_revenue, statistics.yesterday_revenue)">
            较昨日 {{ getTrendText(statistics.today_revenue, statistics.yesterday_revenue) }}
          </text>
        </view>
        <view class="stats-item">
          <text class="stats-label">今日下单数量(单)</text>
          <text class="stats-value">{{ statistics.today_orders || 0 }}</text>
          <text class="stats-compare">昨日 {{ statistics.yesterday_orders || 0 }}</text>
          <text class="stats-trend" :class="getTrendClass(statistics.today_orders, statistics.yesterday_orders)">
            较昨日 {{ getTrendText(statistics.today_orders, statistics.yesterday_orders) }}
          </text>
        </view>
        <view class="stats-item">
          <text class="stats-label">今日实际收入(元)</text>
          <text class="stats-value">{{ ((statistics.today_revenue || 0) / 100).toFixed(2) }}</text>
          <text class="stats-compare">昨日 ¥{{ ((statistics.yesterday_revenue || 0) / 100).toFixed(2) }}</text>
          <text class="stats-trend" :class="getTrendClass(statistics.today_revenue, statistics.yesterday_revenue)">
            较昨日 {{ getTrendText(statistics.today_revenue, statistics.yesterday_revenue) }}
          </text>
        </view>
      </view>
      
      <!-- 日期筛选器 -->
      <view class="date-filter" @click="showDateRangePicker = true">
        <uni-icons type="calendar" size="16" color="#fff"></uni-icons>
        <text>{{ dateRangeText }}</text>
        <uni-icons type="down" size="14" color="#fff"></uni-icons>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 数据统计卡片 -->
      <uni-card :is-shadow="true" margin="0" padding="10px">
        <view class="stats-tabs">
          <text v-for="(tab, index) in statsTabs" :key="index" :class="['tab-item', { active: currentStatsTab === index }]" @click="currentStatsTab = index">{{ tab }}</text>
        </view>
        <view class="stats-summary">
          <text>总订单: <text class="amount">¥{{ ((statistics.total_revenue || 0) / 100).toFixed(2) }}</text></text>
          <text>实际收入: <text class="amount">¥{{ ((statistics.total_revenue || 0) / 100).toFixed(2) }}</text></text>
        </view>
        <uni-grid :column="3" :show-border="false" :square="true">
          <uni-grid-item v-for="(item, index) in detailedStats" :key="index">
            <view class="stats-grid-item">
              <view class="stats-icon" :style="{ backgroundColor: getPaymentIconColor(index) }">
                <uni-icons :type="getPaymentIcon(item.label)" size="20" color="#fff"></uni-icons>
              </view>
              <text class="stats-label">{{ item.label }}</text>
              <text class="stats-value">{{ item.value }}</text>
              <text class="stats-sub-value">{{ item.subValue }}</text>
            </view>
          </uni-grid-item>
        </uni-grid>
      </uni-card>

      <!-- 订单趋势图表 -->
      <uni-card title="订单趋势" :is-shadow="true" margin="15px 0 0 0" padding="10px">
        <view class="chart-container">
          <qiun-data-charts 
            type="line" 
            :opts="lineOpts" 
            :chartData="revenueChartData" 
            :canvas2d="true"
            canvasId="revenue-trend-chart" />
        </view>
      </uni-card>

      <!-- 支付方式分布 -->
      <uni-card title="支付方式分布" :is-shadow="true" margin="15px 0 0 0" padding="10px">
        <view class="chart-container">
          <qiun-data-charts 
            type="pie" 
            :opts="pieOpts" 
            :chartData="paymentChartData" 
            :canvas2d="true"
            canvasId="payment-type-chart" />
        </view>
      </uni-card>

      <!-- 订单记录列表 -->
      <uni-card title="订单记录" :is-shadow="true" margin="15px 0 0 0" padding="10px">
        <view class="list-header">
          <view class="list-filter">
            <uni-segmented-control :current="0" :values="['全部', '支付', '退款']" @clickItem="onFilterChange" styleType="button" activeColor="#1976d2"></uni-segmented-control>
          </view>
          <view class="list-action">
            <button class="btn-export" @click="exportOrders">
              <uni-icons type="download" size="14" color="#fff"></uni-icons>
              <text>导出记录</text>
            </button>
          </view>
        </view>
        <view class="transaction-list">
          <view v-if="transactions.length === 0" class="empty-tip">
            <image class="empty-image" src="/static/empty-data.png" mode="aspectFit"></image>
            <text>暂无订单记录</text>
          </view>
          <view v-else v-for="(item, index) in transactions" :key="index" class="transaction-item" @click="viewOrderDetail(item.id)">
            <view class="transaction-info">
              <view class="transaction-title">
                <text class="transaction-type" :class="getTypeClass(item.type)">{{ getOrderTypeText(item.type) }}</text>
                <text class="transaction-no">订单号: {{ item.order_no || '-' }}</text>
              </view>
              <view class="transaction-desc">
                <text>{{ formatDate(item.created_at) }}</text>
                <text>{{ item.payment_type_text }}</text>
              </view>
            </view>
            <view class="transaction-amount" :class="{'income': item.amount > 0, 'expense': item.amount < 0}">
              {{ item.amount > 0 ? '+' : '' }}{{ (item.amount / 100).toFixed(2) }}
            </view>
          </view>
        </view>
        <view class="load-more" v-if="hasMoreTransactions">
          <button class="btn-load-more" @click="loadMoreTransactions">
            <text>加载更多</text>
            <uni-icons type="bottom" size="14" color="#666"></uni-icons>
          </button>
        </view>
      </uni-card>
    </view>


    <!-- 日期范围选择弹窗 -->
    <uni-popup ref="datePopup" type="bottom" @change="popupChange">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择日期范围</text>
          <text class="popup-close" @click="showDateRangePicker = false">关闭</text>
        </view>
        <view class="popup-body">
          <view class="date-range-options">
            <view class="date-option" @click="selectDateRange('today')">
              <text :class="{'selected': dateRange === 'today'}">今日</text>
            </view>
            <view class="date-option" @click="selectDateRange('yesterday')">
              <text :class="{'selected': dateRange === 'yesterday'}">昨日</text>
            </view>
            <view class="date-option" @click="selectDateRange('week')">
              <text :class="{'selected': dateRange === 'week'}">本周</text>
            </view>
            <view class="date-option" @click="selectDateRange('month')">
              <text :class="{'selected': dateRange === 'month'}">本月</text>
            </view>
            <view class="date-option" @click="selectDateRange('custom')">
              <text :class="{'selected': dateRange === 'custom'}">自定义</text>
            </view>
          </view>
          <view class="custom-date-range" v-if="dateRange === 'custom'">
            <view class="date-picker-container">
              <picker mode="date" :value="startDateStr" @change="onStartDateChange">
                <view class="date-picker">
                  <uni-icons type="calendar" size="16" color="#666"></uni-icons>
                  <text>开始日期: {{ startDateStr }}</text>
                </view>
              </picker>
            </view>
            <view class="date-picker-container">
              <picker mode="date" :value="endDateStr" @change="onEndDateChange">
                <view class="date-picker">
                  <uni-icons type="calendar" size="16" color="#666"></uni-icons>
                  <text>结束日期: {{ endDateStr }}</text>
                </view>
              </picker>
            </view>
          </view>
          <button class="btn-confirm" @click="confirmDateRange">确认</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue';
import { mapState } from 'vuex';
import dayjs from 'dayjs';
import { useAppStore } from '@/stores/app';
import { fetchOrderStatistics, fetchOrders, getExportOrdersUrl } from '@/api/order';

export default {
  setup() {
    const appStore = useAppStore();
    return { appStore };
  },
  data() {
    return {
      statusBarHeight: 0,
      // 筛选条件
      dateRange: 'month', // today, yesterday, week, month, custom
      startDate: null,
      endDate: null,
      startDateStr: '',
      endDateStr: '',
      showDateRangePicker: false,
      currentFilter: 0, // 0: 全部, 1: 支付, 2: 退款
      
      // 数据
      statistics: {
        total_revenue: 0,
        today_revenue: 0,
        yesterday_revenue: 0,
        today_orders: 0,
        yesterday_orders: 0,
        week_revenue: 0,
        month_revenue: 0,
        payment_types: [],
        order_status: [],
        revenue_by_day: [],
        revenue_by_store: [],
        revenue_by_venue: []
      },
      storeList: [],
      transactions: [],
      currentPage: 1,
      pageSize: 10,
      totalTransactions: 0,
      
      // 图表配置
      // 统计选项卡
      statsTabs: ['今日', '昨日', '近7天', '本月', '全部'],
      currentStatsTab: 0,
      
      // 详细统计数据
      detailedStats: [
        { label: '微信支付', value: '0', subValue: '退款: 0' },
        { label: '支付宝', value: '0', subValue: '退款: 0' },
        { label: '余额支付', value: '0', subValue: '退款: 0' },
      ],
      
      lineOpts: {
        color: ["#1976d2", "#4caf50"],
        padding: [15, 15, 15, 15],
        legend: {
          show: false
        },
        xAxis: {
          boundaryGap: true,
          axisLine: {
            show: true
          },
          axisLabel: {
            margin: 8,
            fontSize: 12
          }
        },
        yAxis: {
          splitLine: {
            show: true,
            lineStyle: {
              color: ['#eee']
            }
          },
          axisLabel: {
            margin: 8,
            fontSize: 12
          }
        },
        extra: {
          line: {
            type: "curve",
            width: 2,
            activeType: "hollow"
          }
        }
      },
      pieOpts: {
        color: ["#1976d2", "#4caf50", "#ff9800", "#9c27b0", "#f44336"],
        padding: [5, 5, 5, 5],
        legend: {
          show: true,
          position: "right",
          lineHeight: 25
        },
        extra: {
          pie: {
            labelWidth: 15,
            border: false,
            borderWidth: 3,
            borderColor: "#FFFFFF",
            linearType: "custom"
          }
        }
      },
      revenueChartData: {
        categories: [],
        series: [{
          name: "订单",
          data: []
        }]
      },
      paymentChartData: {
        series: []
      }
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
    currentStoreName() {
      return this.appStore.currentStore?.name || '加载中...';
    },
    currentStoreStatus() {
      if (!this.appStore.currentStore) return { text: '未知', type: 'info' };
      const status = this.appStore.currentStore.status;
      if (status === 2) return { text: '已打烊', type: 'error' };
      if (status === 1) return { text: '试营业', type: 'success' };
      return { text: '筹备中', type: 'warning' };
    },
    dateRangeText() {
      switch (this.dateRange) {
        case 'today':
          return '今日';
        case 'yesterday':
          return '昨日';
        case 'week':
          return '本周';
        case 'month':
          return '本月';
        case 'custom':
          return `${this.startDateStr} 至 ${this.endDateStr}`;
        default:
          return '选择日期';
      }
    },
    hasMoreTransactions() {
      return this.transactions.length < this.totalTransactions;
    }
  },
  onLoad() {
    this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight || 44;
    this.initDateRange();
    // 加载订单数据
    this.loadOrderData();
  },
  onShow() {
    // 每次页面显示时重新加载数据
    this.appStore.getAllStores(); // 确保获取最新的门店列表
    if (this.appStore.currentStoreId) {
      console.log('当前门店ID:', this.appStore.currentStoreId);
      this.loadOrderData();
    } else {
      console.log('未选择门店');
      uni.showToast({
        title: '请先在首页选择门店',
        icon: 'none'
      });
    }
  },
  watch: {
    showDateRangePicker(val) {
      if (val) {
        this.$refs.datePopup.open();
      } else {
        this.$refs.datePopup.close();
      }
    },
    // 监听当前门店ID变化
    'appStore.currentStoreId': {
      handler(newVal) {
        if (newVal) {
          console.log('门店ID变化，重新加载数据:', newVal);
          this.currentPage = 1;
          this.loadOrderData();
        }
      },
      immediate: true
    },
    // 监听统计选项卡变化
    currentStatsTab(newVal) {
      // 根据选项卡更新详细统计数据
      this.updateDetailedStats();
    }
  },
  methods: {
    // 初始化日期范围
    initDateRange() {
      const now = new Date();
      const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      
      this.startDate = Math.floor(startOfMonth.getTime() / 1000);
      this.endDate = Math.floor(now.getTime() / 1000);
      
      this.startDateStr = dayjs(startOfMonth).format('YYYY-MM-DD');
      this.endDateStr = dayjs(now).format('YYYY-MM-DD');
    },
    
    // 加载订单数据
    async loadOrderData() {
      uni.showLoading({
        title: '加载中...',
        mask: true
      });
      
      try {
        await Promise.all([
          this.loadStatistics(),
          this.loadTransactions()
        ]);
      } catch (error) {
        console.error('加载数据失败', error);
      } finally {
        uni.hideLoading();
      }
    },
    
    // 加载订单统计数据
    async loadStatistics() {
      try {
        const params = this.getFilterParams();
        console.log('订单统计参数:', params);
        const res = await fetchOrderStatistics(params);
        
        console.log('API响应:', res);
        
        // 检查API响应格式
        if (res) {
          console.log('订单统计数据:', res);
          // 将API返回的数据映射到组件需要的格式
          this.statistics = {
            total_revenue: res.total_revenue || 0,
            today_revenue: res.today_revenue || 0,
            yesterday_revenue: res.yesterday_revenue || 0,
            today_orders: res.today_orders || 0,
            yesterday_orders: res.yesterday_orders || 0,
            week_revenue: res.week_revenue || 0,
            month_revenue: res.month_revenue || 0,
            payment_types: res.payment_types || [],
            order_status: res.order_status || [],
            revenue_by_day: res.revenue_by_day || [],
            revenue_by_store: res.revenue_by_store || [],
            revenue_by_venue: res.revenue_by_venue || []
          };
          
          // 更新详细统计数据
          this.updateDetailedStats();
          
          // 延迟更新图表，确保DOM已经渲染
          setTimeout(() => {
            this.updateRevenueChart(this.statistics.revenue_by_day || []);
            this.updatePaymentChart(this.statistics.payment_types || []);
          }, 300);
        } else {
          console.error('加载订单统计数据失败:', res);
          uni.showToast({
            title: '加载订单统计数据失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载订单统计数据失败', error);
        uni.showToast({
          title: '加载订单统计数据失败',
          icon: 'none'
        });
      }
    },
    
    // 更新详细统计数据
    updateDetailedStats() {
      // 根据当前选中的统计选项卡更新详细统计数据
      const paymentTypes = this.statistics.payment_types || [];
      
      // 默认值
      this.detailedStats = [
        { label: '微信支付', value: '¥0.00', subValue: '退款: ¥0.00' },
        { label: '支付宝', value: '¥0.00', subValue: '退款: ¥0.00' },
        { label: '余额支付', value: '¥0.00', subValue: '退款: ¥0.00' },
      ];
      
      // 如果有支付方式数据，更新详细统计数据
      if (paymentTypes.length > 0) {
        paymentTypes.forEach((item, index) => {
          if (index < this.detailedStats.length && item) {
            const amount = ((item.amount || 0) / 100).toFixed(2);
            const refund = ((item.refund || 0) / 100).toFixed(2);
            
            this.detailedStats[index].value = `¥${amount}`;
            this.detailedStats[index].subValue = `退款: ¥${refund}`;
            
            // 如果有类型名称，更新标签
            if (item.type) {
              this.detailedStats[index].label = item.type;
            }
          }
        });
      }
    },
    
    // 加载订单记录
    async loadTransactions() {
      try {
        const params = {
          ...this.getFilterParams(),
          page: this.currentPage,
          pageSize: this.pageSize
        };
        
        // 根据当前筛选条件添加类型筛选
        if (this.currentFilter === 1) {
          params.type = 'payment';
        } else if (this.currentFilter === 2) {
          params.type = 'refund';
        }
        
        const res = await fetchOrders(params);
        
        console.log('订单记录响应:', res);
        
        if (res) {
          if (this.currentPage === 1) {
            this.transactions = res.list || [];
          } else {
            this.transactions = [...this.transactions, ...(res.list || [])];
          }
          this.totalTransactions = res.total || 0;
        } else {
          console.error('加载订单记录失败:', res);
          uni.showToast({
            title: '加载订单记录失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载订单记录失败', error);
        uni.showToast({
          title: '加载订单记录失败',
          icon: 'none'
        });
      }
    },
    
    // 筛选条件变更
    onFilterChange(e) {
      this.currentFilter = e.currentIndex;
      this.currentPage = 1;
      this.loadTransactions();
    },
    
    // 加载更多订单记录
    loadMoreTransactions() {
      this.currentPage++;
      this.loadTransactions();
    },
    
    // 更新订单趋势图表
    updateRevenueChart(revenueByDay) {
      try {
        if (!revenueByDay || revenueByDay.length === 0) {
          this.revenueChartData = {
            categories: [],
            series: [{
              name: "订单",
              data: []
            }]
          };
          return;
        }
        
        const categories = [];
        const data = [];
        const orderCounts = [];
        
        // 确保数据有效
        revenueByDay.forEach(item => {
          if (item && item.day) {
            categories.push(item.day.substring(5)); // 只显示月-日
            data.push(parseFloat(((item.amount || 0) / 100).toFixed(2)));
            orderCounts.push(item.count || 0);
          }
        });
        
        // 如果没有数据，添加一个默认数据点
        if (categories.length === 0) {
          categories.push('无数据');
          data.push(0);
          orderCounts.push(0);
        }
        
        this.revenueChartData = {
          categories,
          series: [
            {
              name: "收入(元)",
              data
            },
            {
              name: "订单数",
              data: orderCounts
            }
          ]
        };
        console.log('订单趋势图表数据:', this.revenueChartData);
      } catch (error) {
        console.error('更新订单趋势图表失败:', error);
        this.revenueChartData = {
          categories: ['无数据'],
          series: [{
            name: "订单",
            data: [0]
          }]
        };
      }
    },
    
    // 更新支付方式分布图表
    updatePaymentChart(paymentTypes) {
      try {
        if (!paymentTypes || paymentTypes.length === 0) {
          this.paymentChartData = { 
            series: [{
              name: '无数据',
              data: 1
            }]
          };
          return;
        }
        
        const series = [];
        
        // 确保数据有效
        paymentTypes.forEach(item => {
          if (item) {
            // 如果type为空，使用"未知支付方式"
            const typeName = item.type ? item.type : '未知支付方式';
            series.push({
              name: typeName,
              data: parseFloat(((item.amount || 0) / 100).toFixed(2))
            });
          }
        });
        
        // 如果没有数据，添加一个默认数据点
        if (series.length === 0) {
          series.push({
            name: '无数据',
            data: 1
          });
        }
        
        this.paymentChartData = { series };
        console.log('支付方式分布图表数据:', this.paymentChartData);
      } catch (error) {
        console.error('更新支付方式分布图表失败:', error);
        this.paymentChartData = { 
          series: [{
            name: '无数据',
            data: 1
          }]
        };
      }
    },
    
    // 获取筛选参数
    getFilterParams() {
      const params = {
        start_time: this.startDate,
        end_time: this.endDate
      };
      
      // 使用appStore中的当前门店ID
      if (this.appStore.currentStoreId) {
        params.store_id = this.appStore.currentStoreId;
      }
      
      return params;
    },
    
    // 选择日期范围
    selectDateRange(range) {
      this.dateRange = range;
      
      const now = new Date();
      let startDate, endDate;
      
      switch (range) {
        case 'today':
          startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
          endDate = now;
          break;
        case 'yesterday':
          startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
          endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 23, 59, 59);
          break;
        case 'week':
          const day = now.getDay() || 7; // 将周日的0转为7
          startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day + 1);
          endDate = now;
          break;
        case 'month':
          startDate = new Date(now.getFullYear(), now.getMonth(), 1);
          endDate = now;
          break;
        case 'custom':
          // 保持当前自定义日期不变
          return;
      }
      
      if (startDate && endDate) {
        this.startDate = Math.floor(startDate.getTime() / 1000);
        this.endDate = Math.floor(endDate.getTime() / 1000);
        this.startDateStr = dayjs(startDate).format('YYYY-MM-DD');
        this.endDateStr = dayjs(endDate).format('YYYY-MM-DD');
      }
    },
    
    // 确认日期范围选择
    confirmDateRange() {
      this.showDateRangePicker = false;
      this.currentPage = 1;
      this.loadOrderData();
    },
    
    // 开始日期变更
    onStartDateChange(e) {
      this.startDateStr = e.detail.value;
      const startDate = new Date(e.detail.value);
      this.startDate = Math.floor(startDate.getTime() / 1000);
    },
    
    // 结束日期变更
    onEndDateChange(e) {
      this.endDateStr = e.detail.value;
      const endDate = new Date(e.detail.value);
      endDate.setHours(23, 59, 59);
      this.endDate = Math.floor(endDate.getTime() / 1000);
    },
    
    // 弹窗状态变化
    popupChange(e) {
      if (e.show === false) {
        this.showDateRangePicker = false;
      }
    },
    
    // 查看订单详情
    viewOrderDetail(id) {
      uni.navigateTo({
        url: `/pages/orders/detail?id=${id}`
      });
    },
    
    // 导出订单记录
    exportOrders() {
      // 检查是否有当前门店
      if (!this.appStore.currentStoreId) {
        uni.showModal({
          title: '提示',
          content: '请先选择一个门店再导出订单记录',
          showCancel: false
        });
        return;
      }
      
      const params = this.getFilterParams();
      const exportUrl = getExportOrdersUrl(params);
      
      // 根据平台使用不同的方式打开链接
      // #ifdef APP-PLUS
      plus.runtime.openURL(exportUrl);
      // #endif
      
      // #ifdef H5
      window.open(exportUrl, '_blank');
      // #endif
      
      // #ifdef MP
      uni.showToast({
        title: '小程序环境不支持导出功能',
        icon: 'none'
      });
      // #endif
    },
    
    // 格式化日期
    formatDate(timestamp) {
      return dayjs(timestamp * 1000).format('YYYY-MM-DD HH:mm');
    },
    
    // 获取订单类型文本
    getOrderTypeText(type) {
      const typeMap = {
        'payment': '支付',
        'refund': '退款',
        'recharge': '充值',
        'withdraw': '提现'
      };
      return typeMap[type] || type;
    },
    
    // 获取订单类型样式类
    getTypeClass(type) {
      const classMap = {
        'payment': 'type-payment',
        'refund': 'type-refund',
        'recharge': 'type-recharge',
        'withdraw': 'type-withdraw'
      };
      return classMap[type] || '';
    },
    
    // 获取趋势文本
    getTrendText(current, previous) {
      current = current || 0;
      previous = previous || 0;
      if (previous === 0) return '—';
      const change = ((current - previous) / previous * 100).toFixed(1);
      return change > 0 ? `+${change}%` : `${change}%`;
    },
    
    // 获取趋势样式类
    getTrendClass(current, previous) {
      current = current || 0;
      previous = previous || 0;
      if (previous === 0) return '';
      return current >= previous ? 'trend-up' : 'trend-down';
    },
    
    // 获取状态颜色
    getStatusColor(type) {
      const colorMap = {
        'success': 'rgba(76, 217, 100, 0.9)',
        'warning': 'rgba(255, 152, 0, 0.9)',
        'error': 'rgba(244, 67, 54, 0.9)',
        'info': 'rgba(33, 150, 243, 0.9)'
      };
      return colorMap[type] || 'rgba(76, 217, 100, 0.9)';
    },
    
    // 获取支付方式图标
    getPaymentIcon(label) {
      if (label.includes('微信')) return 'weixin';
      if (label.includes('支付宝')) return 'wallet';
      if (label.includes('余额')) return 'wallet';
      return 'paperplane';
    },
    
    // 获取支付方式图标背景色
    getPaymentIconColor(index) {
      const colors = ['#07c160', '#1677ff', '#ff9800'];
      return colors[index % colors.length];
    },
    
    // 切换门店
    switchStore() {
      uni.navigateTo({
        url: '/pages/store/select'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.page-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}

.header-background {
  background: linear-gradient(135deg, #1976d2 0%, #0d47a1 100%);
  padding-bottom: 30px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
  
  &::after {
    content: '';
    position: absolute;
    bottom: -10px;
    left: 0;
    right: 0;
    height: 20px;
    background: #f5f7fa;
    border-radius: 50% 50% 0 0;
  }
}

/* 门店信息样式 */
.store-header {
  display: flex;
  align-items: center;
  padding: 20px 15px 15px;
}

.store-logo-container {
  width: 64px;
  height: 64px;
  background-color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border: 2px solid rgba(255, 255, 255, 0.8);
}

.store-logo {
  width: 54px;
  height: 54px;
  border-radius: 50%;
}

.store-info {
  flex: 1;
}

.store-name {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 6px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.store-status {
  display: flex;
  align-items: center;
}

.status-tag {
  background-color: rgba(76, 217, 100, 0.9);
  color: #fff;
  font-size: 12px;
  padding: 3px 10px;
  border-radius: 12px;
  margin-right: 12px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.switch-store-btn {
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.25);
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 13px;
  transition: all 0.3s;
  
  &:active {
    background-color: rgba(255, 255, 255, 0.4);
  }
  
  text {
    margin-left: 6px;
  }
}

/* 日期筛选器 */
.date-filter {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.15);
  margin: 0 15px;
  padding: 6px 15px;
  border-radius: 20px;
  font-size: 14px;
  
  text {
    margin: 0 8px;
  }
}

/* 今日数据统计样式 */
.today-stats {
  display: flex;
  justify-content: space-between;
  padding: 5px 15px 15px;
  position: relative;
  z-index: 1;
}

.stats-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.1);
  margin: 0 5px;
  padding: 12px 8px;
  border-radius: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
  
  &:first-child {
    margin-left: 0;
  }
  
  &:last-child {
    margin-right: 0;
  }
}

.stats-label {
  font-size: 12px;
  opacity: 0.9;
  margin-bottom: 8px;
  text-align: center;
  font-weight: 500;
}

.stats-value {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 6px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.stats-compare {
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 4px;
}

.stats-trend {
  font-size: 12px;
  color: #e6fffb;
  background-color: rgba(0, 0, 0, 0.15);
  padding: 2px 8px;
  border-radius: 10px;
  
  &.trend-up {
    background-color: rgba(76, 217, 100, 0.3);
  }
  
  &.trend-down {
    background-color: rgba(244, 67, 54, 0.3);
  }
}

.main-content {
  margin-top: -20px;
  padding: 0 15px 20px;
  position: relative;
  z-index: 2;
}

.stats-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  padding: 5px;
  background-color: #f0f2f5;
  border-radius: 12px;
  overflow-x: auto;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch;
  
  &::-webkit-scrollbar {
    display: none;
  }
  
  .tab-item {
    padding: 8px 16px;
    border-radius: 10px;
    font-size: 14px;
    background-color: transparent;
    color: #666;
    transition: all 0.3s;
    flex-shrink: 0;
    
    &.active {
      background-color: #fff;
      color: #1976d2;
      font-weight: 600;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    }
  }
}

.stats-summary {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 14px;
  background-color: rgba(25, 118, 210, 0.05);
  padding: 12px 15px;
  border-radius: 10px;
  
  .amount {
    color: #f56c6c;
    font-weight: bold;
  }
}

.stats-grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 15px 0;
  background-color: #fff;
  border-radius: 10px;
  margin: 5px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  
  &:active {
    background-color: #f9f9f9;
  }
  
  .stats-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 8px;
  }

  .stats-label {
    font-size: 13px;
    color: #666;
    margin-bottom: 8px;
  }
  
  .stats-value {
    font-size: 20px;
    font-weight: bold;
    margin: 4px 0;
    color: #333;
  }
  
  .stats-sub-value {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
  }
}

.chart-container {
  height: 500rpx;
  width: 100%;
  margin-bottom: 20rpx;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
  
  .list-filter {
    flex: 1;
  }
  
  .btn-export {
    display: flex;
    align-items: center;
    font-size: 13px;
    padding: 6px 16px;
    background-color: #1976d2;
    color: #fff;
    border-radius: 6px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    transition: all 0.3s;
    
    text {
      margin-left: 4px;
    }
    
    &:active {
      background-color: #1565c0;
      transform: translateY(1px);
    }
  }
}

.transaction-list {
  .empty-tip {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    color: #999;
    font-size: 14px;
    
    .empty-image {
      width: 120px;
      height: 120px;
      margin-bottom: 15px;
      opacity: 0.6;
    }
  }
  
  .transaction-item {
    display: flex;
    justify-content: space-between;
    padding: 15px;
    border-bottom: 1px solid #eee;
    background-color: #fff;
    border-radius: 10px;
    margin-bottom: 10px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    transition: all 0.3s;
    
    &:active {
      background-color: #f9f9f9;
    }
    
    .transaction-info {
      flex: 1;
      
      .transaction-title {
        margin-bottom: 8px;
        
        .transaction-type {
          font-size: 15px;
          color: #333;
          font-weight: bold;
          margin-right: 10px;
          background-color: #f0f2f5;
          padding: 2px 8px;
          border-radius: 4px;
          
          &.type-payment {
            background-color: rgba(76, 217, 100, 0.1);
            color: #4cd964;
          }
          
          &.type-refund {
            background-color: rgba(244, 67, 54, 0.1);
            color: #f44336;
          }
          
          &.type-recharge {
            background-color: rgba(33, 150, 243, 0.1);
            color: #2196f3;
          }
          
          &.type-withdraw {
            background-color: rgba(255, 152, 0, 0.1);
            color: #ff9800;
          }
        }
        
        .transaction-no {
          font-size: 13px;
          color: #999;
        }
      }
      
      .transaction-desc {
        font-size: 13px;
        color: #999;
        
        text {
          margin-right: 15px;
          display: inline-block;
        }
      }
    }
    
    .transaction-amount {
      font-size: 17px;
      font-weight: bold;
      align-self: center;
      
      &.income {
        color: #f56c6c;
      }
      
      &.expense {
        color: #67c23a;
      }
    }
  }
}

.load-more {
  text-align: center;
  margin: 20px 0;
  
  .btn-load-more {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    padding: 8px 30px;
    background-color: #f5f5f5;
    color: #666;
    border-radius: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    transition: all 0.3s;
    
    text {
      margin-right: 4px;
    }
    
    &:active {
      background-color: #e8e8e8;
    }
  }
}

.popup-content {
  background-color: #fff;
  border-radius: 20px 20px 0 0;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  background-color: #f8f8f8;
}

.popup-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 14px;
  color: #1976d2;
  padding: 5px 10px;
}

.popup-body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
  
  .date-range-options {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
    
    .date-option {
      flex: 1;
      min-width: 80px;
      text-align: center;
      padding: 10px 0;
      background-color: #f5f7fa;
      border-radius: 8px;
      font-size: 14px;
      color: #333;
      transition: all 0.3s;
      
      &:active {
        background-color: #e8e8e8;
      }
      
      .selected {
        color: #1976d2;
        font-weight: bold;
      }
    }
  }
  
  .custom-date-range {
    margin-top: 20px;
    
    .date-picker-container {
      margin-bottom: 15px;
      
      .date-picker {
        display: flex;
        align-items: center;
        padding: 12px 15px;
        border: 1px solid #ddd;
        border-radius: 8px;
        font-size: 14px;
        color: #333;
        background-color: #f9f9f9;
        
        text {
          margin-left: 8px;
        }
      }
    }
  }
  
  .btn-confirm {
    margin-top: 25px;
    width: 100%;
    height: 44px;
    line-height: 44px;
    background-color: #1976d2;
    color: #fff;
    font-size: 16px;
    border-radius: 8px;
    font-weight: 500;
    box-shadow: 0 2px 6px rgba(25, 118, 210, 0.2);
    transition: all 0.3s;
    
    &:active {
      background-color: #1565c0;
      transform: translateY(1px);
    }
  }
}

/* 卡片样式优化 */
:deep(.uni-card) {
  margin: 10px 0;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05) !important;
  overflow: hidden;
  
  .uni-card__header {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    
    .uni-card__header-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }
  
  .uni-card__content {
    padding: 15px;
  }
}

/* 图表容器优化 */
:deep(.qiun-charts) {
  background-color: #fff;
  border-radius: 8px;
  padding: 10px;
}
</style>
